/**
* Copyright @ 2023 iAuto (Shanghai) Co., Ltd.
* All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are NOT permitted except as agreed by
* iAuto (Shanghai) Co., Ltd.
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
*/


import React, { useEffect, useCallback, useRef } from 'react';
import { connect } from 'dva';
import { Prompt } from 'dva/router';
import { withRouter } from 'react-router-dom';
import IAutoPage from '@/components/soa/IAutoPage';
import { useMount, useUnmount, useSize } from 'ahooks';
import { ExclamationCircleOutlined } from '@ant-design/icons';
import classNames from 'classnames';
import { Modal } from 'antd';

import Blocks from './components/Blocks';
import Title from './components/Title';

import { getSkillJson } from '@/lib/custom-extension';

import './index.less';
import styles from './index.less';
// import Loading from '@/components/Loading/Loading';
import { getEditerCompeteList, getSkillList } from '@/services/httpService';
import { replaceKeys } from '@/utils';
import projectData from '@/lib/default-project/project-data';
import template from '@/lib/default-project/template.json';
import staticData from '@/lib/db/index.json';
import log from '@/lib/log';

const mapStateToProps = (state: any) => ({
  vm: state.vm,
  editGlobal: state.editGlobal,
});

const Edit: React.FC<any> = ({ dispatch, location, ...props }) => {
  const modelCode = location.query.modelCode;
  const {
    seriesCode = '',
    sceneUuid,
  } = location.query;
  const blockRef = useRef(null);
  const blockSize = useSize(blockRef);

  const {
    vm,
    editGlobal: {
      isLoading,
      sceneUuid: id,
      name,
      modalMsg,
      modalOk,
      modalDisabled,
      projectChanged,
      // loadingList,
    },
  } = props;
  // console.log('🚀 ~ file: index.tsx ~ line 61 ~ loadingList', loadingList);

  const setId = useCallback((id: string) => {
    dispatch({
      type: 'editGlobal/setGlobalState',
      payload: {
        sceneUuid: id,
      },
    });
  }, []);

  const handleCheckCode = [modelCode, seriesCode].every(Boolean);

  useEffect(() => {
    if (!name) {
      const title = getTitle();

      dispatch({
        type: 'editGlobal/setGlobalState',
        payload: {
          name: title,
        },
      });
    }
  }, [name]);

  // 检测是否存在车系车系
  useEffect(() => {
    if (!handleCheckCode) {
      Modal.confirm({
        title: '提示',
        icon: <ExclamationCircleOutlined />,
        content: '未解析到车型车系',
        okText: '确认',
        cancelText: '取消',
        // onOk(...args) { },
      });
      throw '未解析到车型车系';
    }
  }, [handleCheckCode]);

  const leavePageConfirm = useCallback(
    (e: BeforeUnloadEvent) => {
      if (projectChanged) {
        // both methods of returning a value may be necessary for browser compatibility
        (e || window.event).returnValue = true;
        return true;
      }
      return; // Returning undefined prevents the prompt from coming up
    },
    [projectChanged],
  );

  // 检测有没有提示 modal
  useEffect(() => {
    if (modalMsg && !modalDisabled) {
      Modal.warning({
        // content: modalMsg,
        content: modalMsg,
        okText: '确认',
        keyboard: false,
        onOk() {
          if (typeof modalOk === 'function') {
            modalOk();
          }
          dispatch({
            type: 'editGlobal/setGlobalState',
            payload: {
              modalMsg: '',
              modalOk: null,
              modalDisabled: true,
            },
          });
        },
      });
    }
  }, [modalMsg, modalDisabled]);

  useMount(async () => {
    setId(sceneUuid);
    handleInit();

    handleGetAbilityList();
    handleGetEditerCompeteList();
    // getAbilityList();
  });

  const handleGetEditerCompeteList = async () => {
    dispatch({
      type: 'editGlobal/setLoading',
      payload: {
        apiName: 'handleGetEditerCompeteList',
        loading: true,
      },
    });
    try {
      const { data: competeListData, statusCode } = await getEditerCompeteList({
        seriesCode,
        modelCode,
      });
      // console.log("🚀 ~ file: index.tsx ~ line 181 ~ handleGetEditerCompeteList ~ competeListData", competeListData)

      if (statusCode !== '0') {
        // message.error(errorMsg);
        // dispatch({
        //   type: 'editGlobal/setModalConfirm',
        //   payload: {
        //     msg: '竞合关系获取失败',
        //   },
        // });
        log.error("竞合关系获取失败")
      }

      dispatch({
        type: 'editGlobal/setLoading',
        payload: {
          apiName: 'handleGetEditerCompeteList',
          loading: false,
        },
      });

      const editerRules = {};

      competeListData?.competitions?.forEach((item) => {
        const { skillId, exclusions } = item;
        editerRules[Number(skillId)] = exclusions.map(Number);
      });

      dispatch({
        type: 'editGlobal/setGlobalState',
        payload: {
          editerRules,
        },
      });
    } catch (error) {
      console.log('🚀 ~ file: index.tsx ~ line 175 ~ handleGetEditerCompeteList ~ error', error);
    }
  };

  const handleGetAbilityList = async () => {
    // 加载loading
    dispatch({
      type: 'editGlobal/setLoading',
      payload: {
        apiName: 'handleGetAbilityList',
        loading: true,
      },
    });

    try {
      const {
        data: { skills },
        statusCode,
      } = await getSkillList({ seriesCode, modelCode });
      // console.log("🚀 ~ file: index.tsx ~ line 219 ~ handleGetAbilityList ~ skills", skills)
      if (statusCode !== '0') {
        // message.error(errorMsg);
        dispatch({
          type: 'editGlobal/setModalConfirm',
          payload: {
            msg: '能力获取失败',
          },
        });
        return;
      }

      dispatch({
        type: 'editGlobal/setLoading',
        payload: {
          apiName: 'handleGetAbilityList',
          loading: false,
        },
      });

      if (!skills.length) {
        dispatch({
          type: 'editGlobal/setModalConfirm',
          payload: {
            msg: '暂无能力导入，仅包含基础模块，请导入能力！',
          },
        });

        return;
      }

      const reKeys = {
        inargs: 'inputArgs',
        id: 'ID',
        category: 'className',
        value: 'defaultValue',
      };
      const ignore: string[] = [];
      const json = replaceKeys(skills, reKeys, ignore);
      const { skillJson, skillMap } = getSkillJson(json);

      if (skillJson.length) {
        dispatch({
          type: 'editGlobal/setGlobalState',
          payload: {
            skillJson,
            skillMap
          },
        });
      }
    } catch (error) {
      console.log('🚀 ~ file: index.tsx ~ line 203 ~ handleGetAbilityList ~ error', error);
    }
  };
  // 获取能力列表
  // eslint-disable-next-line
  const getAbilityList = async () => {
    dispatch({
      type: 'editGlobal/setGlobalState',
      payload: {
        loadProgram: true,
      },
    });
    // eslint-disable-next-line
    const { seriesCode = '' } = location.query;
    if (seriesCode && seriesCode) {
      try {

        const { skillJson, skillMap } = getSkillJson(staticData);

        setTimeout(() => {
          dispatch({
            type: 'editGlobal/setGlobalState',
            payload: {
              skillJson, skillMap
            },
          });
        }, 2000);
      } catch (error) {
        console.log('🚀 ~ file: index.tsx ~ line 126 ~ getAbilityList ~ error', error);
      }
    }
  };

  const handleInit = () => {
    // 解决 滚动条问题
    setTimeout(() => {
      const myEvent = new Event('resize');
      window.dispatchEvent(myEvent);
    }, 400);

    // 初始化 vm
    dispatch({
      type: 'vm/init',
    });

    // 进入重置项目状态
    dispatch({
      type: 'status/resetCarState',
    });

    getTitle();
  };

  useUnmount(() => {
    if (typeof window === 'object') {
      window.onbeforeunload = null;
    }
    // 进入重置项目状态
    dispatch({
      type: 'status/resetCarState',
    });

    // clear vm
    dispatch({
      type: 'vm/clear',
    });

    dispatch({
      type: 'editGlobal/resetGlobalState',
      payload: {},
    });
  });

  useEffect(() => {
    if (typeof window === 'object') {
      window.onbeforeunload = (e) => leavePageConfirm(e);
    }
  }, [leavePageConfirm]);

  const handleClear = () => {
    // window.confirm('是否清空积木') && Blocks?.loadDefaultProject()
    Modal.confirm({
      title: '提示',
      icon: <ExclamationCircleOutlined />,
      content: '是否确定清空工作区的所有积木',
      okText: '删除',
      cancelText: '取消',
      onOk() {
        // Blocks?.loadDefaultProject({})
        vm.loadProject(JSON.stringify(projectData(template)))
          .then()
          .catch()
          .then(() => {
            dispatch({
              type: 'editGlobal/setGlobalState',
              payload: {
                projectChanged: false,
              },
            });
          });
      },
    });
  };

  const getTitle = useCallback(() => {
    if (location.query.cnName) {
      return location.query.cnName;
    } else {
      const num = String(Date.now());
      const title = `新建场景${num.slice(num.length - 6)}`;
      return title;
    }
  }, []);

  return (
    <IAutoPage loading={isLoading} className={styles.pd0}>
      <div className={styles.editWrapper}>
        <Prompt
          when={projectChanged}
          message={() => {
            return `是否丢弃当前作品中尚未保存的内容?`;
          }}
        />
        <>
          {handleCheckCode && (
            <div className={styles.editContainer}>
              {/* title */}
              <Title
                blockSize={blockSize}
                title={name}
                vm={vm}
                clear={handleClear}
                projectChanged={projectChanged}
                id={id}
                setId={setId}
                name={name || ''}
              />

              <div className={classNames(styles.fullScreenBlock)}>
                {vm && <Blocks vm={vm} id={id} blockRef={blockRef} location={location} />}
              </div>
            </div>
          )}
        </>
      </div>
    </IAutoPage>
  );
};

export default connect(mapStateToProps)(withRouter(Edit));
